import React, {useState, useEffect} from 'react';

import {
    NavBar,
    Icon,
    Accordion,
    Modal,
    List,
    Button,
    Radio,
    Toast,
    TextareaItem,
    InputItem,
    SearchBar
} from 'antd-mobile';
import AMap from 'AMap';
import mark from "@/assets/svg/mark.svg"
import {GetOrderDetails, PostAddApply, PostCancelApply, PostRefund} from "@/api/tutor/orderList.js"

import {GetListResume, GetListResumeFroSelect} from "@/api/tutor/biographicalNotes.js"
import {ORDER_STATUSES, createInfoWindow} from "@/assets/js/dict";

const prompt = Modal.prompt;

//订单市场的订单详情
const OrderDetails = (props) => {
    // 订单详情
    let [orderDetailsObject, setOrderDetailsObject] = useState({
        students: [],
        learn_hours: '[]'
    })

    // 简历列表
    let [resumeSelectionObj, setResumeSelectionObj] = useState({
        resumeSelectionVisible: false,
        resumeOptionList: [],
        resumeSelection: '',
    })

    // 申请退款
    let [refundDetailsVisible, setRefundDetailsVisible] = useState(false)

    // 退款说明
    let [comment, setComment] = useState('')

    /*
    * 报名一个订单
    * */
    function apply() {
        if (!!resumeSelectionObj.resumeSelection) {
            setResumeSelectionObj({
                resumeSelectionVisible: false,
                resumeOptionList: resumeSelectionObj.resumeOptionList,
                resumeSelection: resumeSelectionObj.resumeSelection
            });
            Modal.alert('提示', '确认选择此份简历报名 ?', [
                {text: '取消', onPress: () => console.log('cancel')},
                {text: '确定', onPress: () => handleSubmit()},
            ])
        } else {
            Toast.show("您还未选择简历，请您选择", 3, false);
        }
    }

    /*
    * 关闭简历选择
    * */
    function closeResumeSelector(){
        setResumeSelectionObj({
            resumeSelectionVisible: false,
            resumeOptionList: resumeSelectionObj.resumeOptionList,
            resumeSelection: resumeSelectionObj.resumeSelection
        });
    }

    /*
    * 渲染简历选择器
    * */
    function renderResumeSelector(item){
        console.log("renderResumeSelector---> ", item);
        setResumeSelectionObj({
            resumeOptionList: resumeSelectionObj.resumeOptionList,
            resumeSelection: item.id,
            resumeSelectionVisible: true,
        })
    }


    // 选中报名
    let handleSubmit = () => {
        console.log('resumeSelection -------->>>', resumeSelectionObj.resumeSelection);
        let postData = {
            tutor_id: JSON.parse(sessionStorage.getItem('userInfo')).id,
            resume_id: resumeSelectionObj.resumeSelection,
            order_id: orderDetailsObject.id
        };

        PostAddApply(postData).then(res => {
            if (res.code === '000000') {
                Toast.success('订单报名成功', 3, function () {
                    props.history.push("/preOrder");
                })
            } else {
                Toast.fail(res.message ? res.message : "出错了，请联系平台", 3, true);
            }
        }).catch(err => {

        })
    };

    // 家教取消报名
    let handleCancelApply = (note) => {
        let postData = {
            tutor_id: JSON.parse(sessionStorage.getItem('userInfo')).id,
            order_id: orderDetailsObject.id,
            note: note
        }

        PostCancelApply(postData).then(res => {
            if (res.code == '000000') {
                Toast.success('取消报名成功', 3, function () {
                    props.history.goBack()
                })
            }
        }).catch(err => {

        })
    }

    // 确定退款
    let handleRefund = () => {
        let postData = {
            tutor_id: JSON.parse(sessionStorage.getItem('userInfo')).id,
            order_id: orderDetailsObject.id,
            comment,
        };
        console.log('postData ----->>>', postData);
        PostRefund(postData).then(res => {
            if (res.code == '000000') {
                Toast.success('退款申请成功', 3, function () {
                    setRefundDetailsVisible(false);
                    props.history.goBack()
                })
            }
        }).catch(err => {
            console.error(err);
        })
    }

    function btnFn() {
        const status = orderDetailsObject.status;
        if (props.location.data && props.location.data._type) {
            return (
                <div className="form-footer">
                    <Button type="primary"
                            style={{display: (props.location.data._type === 'pending' && status === ORDER_STATUSES.SELECTED) ? 'block' : 'none'}}
                            onClick={() => {
                                props.history.push({
                                    pathname: '/payOfOrder',
                                    data: orderDetailsObject
                                })
                            }}
                    >支付</Button>
                    <Button type="warning"
                            style={{display: (props.location.data._type === 'pending' && orderDetailsObject.isApplied && (status === ORDER_STATUSES.SELECTED || status === ORDER_STATUSES.PUBLISH)) ? 'block' : 'none'}}
                            onClick={() => {
                                prompt(
                                    '订单取消说明',
                                    '',
                                    [
                                        {text: '取消'},
                                        {text: '提交', onPress: note => handleCancelApply(note)},
                                    ],
                                    'default',
                                )
                            }}
                    >取消报名</Button>
                    <Button type="primary"
                            style={{display: props.location.data._type === 'history' && (status === ORDER_STATUSES.NO_DEAL || status === ORDER_STATUSES.PAYED || status === ORDER_STATUSES.UNSATISFACTORY) ? 'block' : 'none'}}
                            onClick={() => {
                                setRefundDetailsVisible(true)
                            }}
                    >退款申请</Button>
                </div>
            )
        } else {
            return (
                <div className="form-footer">
                    <Button type="primary" onClick={() => {
                        setResumeSelectionObj({
                            resumeSelectionVisible: true,
                            resumeOptionList: resumeSelectionObj.resumeOptionList
                        })
                    }}
                    >报名</Button>
                </div>
            )
        }
    }

    useEffect(() => {

        let postData = {};
        let id = sessionStorage.getItem("order_id");
        if (!!id) {
            postData.order_id = id;
            postData.tutor_id = JSON.parse(sessionStorage.getItem('userInfo')).id
        } else {
            if (props.location.data._type == 'pending') {
                postData.order_id = props.location.data.order_id;
                sessionStorage.setItem("order_id", postData.order_id);
            } else {
                postData.order_id = props.location.data.id;
                sessionStorage.setItem("order_id", postData.order_id);
            }
        }

        GetOrderDetails(postData).then(res => {
            if (res.code == '000000') {
                let obj = res.responseData;
                setOrderDetailsObject(obj);

                //加载地图
                if (null !== obj.longitude && null !== obj.latitude) {
                    let pp = [obj.longitude, obj.latitude];
                    let mapInstance = new AMap.Map('amap', {
                        resizeEnable: true,
                        zoomEnable: true,
                        dragEnable: true,
                        center: pp,//传入地址的经纬度
                        zoom: 13
                    });

                    mapInstance.on('complete', function () {
                        AMap.plugin(['AMap.Marker', 'AMap.LngLat', 'AMap.Pixel', 'AMap.Icon', 'AMap.Geocoder'], () => {
                            let markPoint = new AMap.Marker({
                                position: new AMap.LngLat(obj.longitude, obj.latitude),
                                offset: new AMap.Pixel(-10, -10),
                                icon: mark, // 添加 Icon 图标 URL
                                title: '上课地址',
                                label: {
                                    // content: '<span style="color: darkgreen; font-size: x-large"><strong>上课地点</strong></span>'
                                }
                            });

                            let geocoder = new AMap.Geocoder({
                                city: "", //城市设为北京，默认：“全国”
                                radius: 1000 //范围，默认：500
                            });

                            let address = ''; // 点击坐标的详细地址； 

                            geocoder.getAddress([obj.longitude, obj.latitude], (status, result) => {
                                if (status === 'complete' && result.regeocode) {
                                    address = result.regeocode.formattedAddress;

                                    //实例化信息窗体
                                    let title = '详细地址：',
                                        content = [];
                                    content.push(address);

                                    //构建自定义信息窗体
                                    let infoWindow = new AMap.InfoWindow({
                                        position: new AMap.LngLat(obj.longitude, obj.latitude),
                                        offset: new AMap.Pixel(24, -4),
                                        autoMove: true,
                                        isCustom: true,  //使用自定义窗体
                                        content: createInfoWindow(title, content.join("<br/>"), mapInstance),
                                    });

                                    infoWindow.open(mapInstance)
                                } else {
                                    console.error('根据经纬度查询地址失败')
                                }
                            });


                            //添加标识物
                            mapInstance.add(markPoint);
                        });
                    });
                }
            }
        }).catch(err => {
            console.log(err);
        });

        // 查询简历列表信息
        GetListResumeFroSelect({tutor_id: JSON.parse(sessionStorage.getItem('userInfo')).id}).then(res => {
            if (res.code == '000000') {
                setResumeSelectionObj({
                    resumeOptionList: res.responseData
                })
            }
        }).catch(err => {
            console.error(err);
        })
    }, [])


    function back() {
        props.history.push({
            pathname: '/mainTutor',
            query: {
                selectedTab: 'lookFor'
            }
        })
    }
    return (
        <div className="order-details">
            <div className="page-title  order-tit">
                <NavBar
                    mode="light"
                    icon={<Icon type="left"/>}
                    onLeftClick={back}
                >
                    订单详情
                </NavBar>

            </div>
            <div className="page-content student-content">
                <div className="student-content-piece">
                    <div className="form-box">
                        <div className="form-tit">
                            <i className="mini-block"/>
                            <strong>基本信息</strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <List.Item>订单编号
                                    <List.Item.Brief>{orderDetailsObject.code}</List.Item.Brief>
                                </List.Item>
                                <List.Item>发布时间
                                    <List.Item.Brief>{orderDetailsObject.audit_time}</List.Item.Brief>
                                </List.Item>
                                <List.Item>家长姓名
                                    <List.Item.Brief>{orderDetailsObject.parent_name}</List.Item.Brief>
                                </List.Item>
                                <List.Item>家长性别
                                    <List.Item.Brief>{orderDetailsObject.parent_gender}</List.Item.Brief>
                                </List.Item>
                                <List.Item multipleLine>
                                    辅导科目
                                    <List.Item.Brief> {orderDetailsObject.subjects} </List.Item.Brief>
                                </List.Item>
                                <List.Item multipleLine>
                                    发布时间
                                    <List.Item.Brief> {orderDetailsObject.audit_time} </List.Item.Brief>
                                </List.Item>
                                <List.Item
                                    extra={orderDetailsObject.class_fee ? "￥" + orderDetailsObject.class_fee / 100 : ''}
                                >课时费</List.Item>
                                <List.Item
                                    extra={orderDetailsObject.brokerage_fee ? "￥" + orderDetailsObject.brokerage_fee / 100 : ''}
                                >中介费</List.Item>
                            </List>
                        </div>
                        <div className="form-tit">
                            <i className="mini-block"/>
                            <strong>
                                可授课时间段
                            </strong>
                        </div>
                        <div className="form-con">
                            <Accordion defaultActiveKey="0" className="my-accordion">
                                {
                                    JSON.parse(orderDetailsObject.learn_hours).length ?
                                        JSON.parse(orderDetailsObject.learn_hours).map((item, index) => {
                                            return <Accordion.Panel header={
                                                <div>
                                                    {item.week}
                                                </div>
                                            } key={index}>
                                                <List className="my-list">
                                                    <List.Item extra={item.startTime}>开始时间</List.Item>
                                                    <List.Item extra={item.endTime}>结束时间</List.Item>
                                                </List>
                                            </Accordion.Panel>
                                        })
                                        :
                                        ''
                                }
                            </Accordion>
                        </div>
                        <div className="form-tit">
                            <i className="mini-block"/>
                            <strong>
                                上课地址
                            </strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <List.Item
                                    multipleLine
                                    platform="android"
                                >
                                    地址<List.Item.Brief> {orderDetailsObject.learn_address} </List.Item.Brief>
                                </List.Item>
                            </List>
                            <div id="amap"
                                 style={orderDetailsObject.longitude !== null ? {width: '100%', height: '300px'} : {}}
                            />
                        </div>
                        <Accordion defaultActiveKey="0" className="my-accordion">
                            {
                                orderDetailsObject.students.map((item, index) => {
                                    return (
                                        <Accordion.Panel header={<b>{`辅导对象信息 ${index + 1}`}</b>} key={index}>
                                            <List>
                                                <List.Item extra={item.name}>性名</List.Item>
                                                <List.Item extra={item.gender}>性别</List.Item>
                                                <List.Item extra={item.grade}>年级</List.Item>
                                                <List.Item
                                                    multipleLine
                                                    platform="android"
                                                >
                                                    辅导对象说明<List.Item.Brief> {item.note} </List.Item.Brief>
                                                </List.Item>
                                            </List>
                                        </Accordion.Panel>

                                    )
                                })
                            }
                        </Accordion>
                        <div className="form-tit">
                            <i className="mini-block"/>
                            <strong>其他信息</strong>
                        </div>
                        <div className="form-con">
                            <List>
                                <List.Item
                                    multipleLine
                                    platform="android"
                                    className="textarea-item"
                                >
                                    工作要求

                                    <List.Item.Brief> {orderDetailsObject.demand} </List.Item.Brief>
                                </List.Item>
                            </List>
                        </div>
                        {
                            btnFn()
                        }

                    </div>

                </div>
            </div>

            {/* 选择简历 */}
            <Modal
                popup
                visible={resumeSelectionObj.resumeSelectionVisible}
                onClose={closeResumeSelector}
                animationType="slide-up"
                footer={[{
                    style: {
                        color: '#fff',
                        border: '1PX solid #e94f4f',
                        borderRadius: '5PX',
                        backgroundColor: '#e94f4f'
                    }, text: '取消', onPress: closeResumeSelector
                }, {
                    style: {
                        color: '#fff',
                        border: '1PX solid #108ee9',
                        borderRadius: '5PX',
                        backgroundColor: '#108ee9'
                    }, text: '确定', onPress: apply
                }]}
            >
                <List renderHeader={<div>请选择简历</div>} className="popup-list">
                    {(resumeSelectionObj.resumeOptionList).map((i, index) => (
                        <Radio.RadioItem key={index} checked={i.id === resumeSelectionObj.resumeSelection}  onChange={() =>renderResumeSelector(i)}>
                            {i.display}
                        </Radio.RadioItem>
                    ))}
                </List>
            </Modal>

            {/* 退款说明 */}
            <Modal
                popup
                visible={refundDetailsVisible}
                animationType="slide-up"
            >
                <List>
                    <TextareaItem
                        placeholder="退款说明"
                        rows={7}
                        onChange={setComment}
                    />
                    <List.Item>
                        <Button type="primary" onClick={handleRefund}>确认</Button>
                    </List.Item>
                </List>
            </Modal>
        </div>
    )

};


export default OrderDetails